"use strict";

exports.__esModule = true;
exports.useDraggable = useDraggable;
// 传入一个拖动的dragEl和一个目标targetEl，拖动dragEl去更新targetEl位置
function useDraggable(targetEl, dragEl, options) {
  if (options === void 0) {
    options = {
      overflow: false
    };
  }
  var transform = {
    offsetX: 0,
    offsetY: 0
  };
  var _options = options,
    overflow = _options.overflow;
  var onMousedown = function onMousedown(e) {
    var downX = e.clientX;
    var downY = e.clientY;
    var _transform = transform,
      offsetX = _transform.offsetX,
      offsetY = _transform.offsetY;
    var targetRect = targetEl.getBoundingClientRect();
    var targetLeft = targetRect.left;
    var targetTop = targetRect.top;
    var targetWidth = targetRect.width;
    var targetHeight = targetRect.height;
    var clientWidth = document.documentElement.clientWidth;
    var clientHeight = document.documentElement.clientHeight;
    var minLeft = -targetLeft + offsetX;
    var minTop = -targetTop + offsetY;
    var maxLeft = clientWidth - targetLeft - targetWidth + offsetX;
    var maxTop = clientHeight - targetTop - targetHeight + offsetY;
    var onMousemove = function onMousemove(e) {
      var moveX = offsetX + e.clientX - downX;
      var moveY = offsetY + e.clientY - downY;
      if (!overflow) {
        moveX = Math.min(Math.max(moveX, minLeft), maxLeft);
        moveY = Math.min(Math.max(moveY, minTop), maxTop);
      }
      transform = {
        offsetX: moveX,
        offsetY: moveY
      };
      if (targetEl) {
        targetEl.style.transform = "translate(" + moveX + "px, " + moveY + "px)";
      }
    };
    var _onMouseup = function onMouseup() {
      console.log('drag on mouse up');
      document.removeEventListener('mousemove', onMousemove);
      document.removeEventListener('mouseup', _onMouseup);
    };
    document.addEventListener('mousemove', onMousemove);
    document.addEventListener('mouseup', _onMouseup);
  };
  var onDraggable = function onDraggable() {
    if (dragEl && targetEl) {
      dragEl.addEventListener('mousedown', onMousedown);
    }
  };
  var offDraggable = function offDraggable() {
    if (dragEl && targetEl) {
      dragEl.removeEventListener('mousedown', onMousedown);
    }
  };
  var resetPosition = function resetPosition() {
    transform = {
      offsetX: 0,
      offsetY: 0
    };
    if (targetEl) {
      targetEl.style.transform = 'none';
    }
  };
  return {
    onDraggable: onDraggable,
    offDraggable: offDraggable,
    resetPosition: resetPosition
  };
}